package icraf.carbon.gui;

import icraf.carbon.core.AbacusContainer;
import icraf.carbon.core.Config;
import icraf.carbon.core.Project;
import icraf.carbon.gui.chart.AbacusPanel;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;


public class ProjectManager {
	private ArrayList<Project> projectList = new ArrayList<Project>();
	private ArrayList<ProjectManagerListener> listener = new ArrayList<ProjectManagerListener>();
	private HashMap<Project, File> projectFile = new HashMap<Project, File>();
	//private HashMap<Project, SummaryPanel> projectChart = new HashMap<Project, SummaryPanel>();
	private HashMap<Project, AbacusPanel> projectChart = new HashMap<Project, AbacusPanel>();
	private Config config = new Config();
	
	public boolean add(Project gp) {
		if (projectList.contains(gp))
			return false;
		else {
			boolean b = projectList.add(gp);
			for (ProjectManagerListener l : listener) {
				l.projectAdded(this, gp);
			}
			return b;
		}
	}
	
	public AbacusPanel getChart(Project p) {
		AbacusPanel c = projectChart.get(p);
		if(c == null) {
			c = new AbacusPanel();
			c.setProject(p);
			projectChart.put(p, c);
		}
		return c;
	}
	
	public boolean add(Project p, File f) {
		putFile(p, f);
		boolean b = add(p);
		
		return b;
	}

	public void putFile(Project p, File f) {
		projectFile.put(p, f);
	}
	
	public File getFile(AbacusContainer p) {
		return projectFile.get(p);
	}

	public void addListener(ProjectManagerListener l) {
		listener.add(l);
	}

	public void clearListener() {
		listener.clear();
	}

	public AbacusContainer get(int index) {
		return projectList.get(index);
	}

	public Project remove(int index) {
		Project gp = projectList.remove(index);
		return  remove(gp);
	}
	
	public Project remove(Project gp) {
		int index = projectList.indexOf(gp);
		projectFile.remove(gp);
		projectChart.remove(gp);
		fireProjectRemoved(gp, index);
		return gp;
	}
	
	private void fireProjectRemoved(Project gp, int index) {
		for (ProjectManagerListener l : listener) {
			l.projectRemoved(this, gp, index);
		}
	}

	public void removeListener(ProjectManagerListener l) {
		listener.remove(l);
	}

	public int size() {
		return projectList.size();
	}

	public Config getConfig() {
		return config;
	}



	
}
